import cloud from '@lafjs/cloud'
const db = cloud.mongo.db
let data

export default async function (ctx: FunctionContext) {
  data = ctx.body.data

  switch (ctx.body.type) {
    case "B1-list"://课程安排表
      return await B1List()
      break;
    case "B1-list-init"://课程安排表重新生成
      return await B1ListInit()
      break;
    case "B3-list":
      return await B3List()
      break;
    case "B3-update":
      return await B3Update()
      break;
    case "update":
      return await cloud.utils.updateData("admin-class-student", data)
      break;
    case "B5-list":
      return await B5List()
      break;
    case "B7-save":
      return await B7Save()
      break;
    case "B7-details":
      return await B7Details()
      break;
    case "student-evaluate-file"://学员评议导入
      return await studentEvaluateFile()
      break;
    case "student-evaluate-list"://学员评议查询-课次
      return await studentEvaluateList()
      break;
    case "student-evaluate-class"://学员评议查询-班级
      return await studentEvaluateClass()
      break;
    case "student-evaluate-delete"://学员评议删除
      return await studentEvaluateDelete()
      break;
    case "student-evaluate-summary"://学员评议汇总
      return await studentEvaluateSummary()
      break;
    default:
      break;
  }
}

//学员评议汇总
async function studentEvaluateSummary() {
  let dbName = "class-student-evaluate"
  const total = await db.collection(dbName).countDocuments(data)
  let form = {
    teachingAttitude1: "",//教学态度
    teachingAttitude2: "",
    teachingAttitude3: "",
    teachingAttitude4: "",
    contentCourses1: "",//教学内容
    contentCourses2: "",
    contentCourses3: "",
    contentCourses4: "",
    trainingMethods1: "",//培训方式
    trainingMethods2: "",
    trainingMethods3: "",
    trainingMethods4: "",
    teachingDevices1: "",//教学手段
    teachingDevices2: "",
    teachingDevices3: "",
    teachingDevices4: "",
    explainDemo1: "",//说明示范
    explainDemo2: "",
    explainDemo3: "",
    explainDemo4: "",
    guidanceAspect1: "",//指导方面
    guidanceAspect2: "",
    guidanceAspect3: "",
    guidanceAspect4: "",
    completionStatus1: "",//完成情况
    completionStatus2: "",
    completionStatus3: "",
    completionStatus4: "",
  }
  for (let key in form) {
    let { prefix, number } = splitString(key)
    let value
    if (number == 1) {
      value = "好"
    } else if (number == 2) {
      value = "较好"
    } else if (number == 3) {
      value = "尚可"
    } else if (number == 4) {
      value = "差"
    }
    let whereJson = { ...data }
    whereJson[prefix] = value
    const count = await db.collection(dbName).countDocuments(whereJson)
    if (count && total) {
      form[key] = (count / total * 100).toFixed(2)
    } else {
      form[key] = 0
    }
  }
  function splitString(str) {
    const match = str.match(/^([^\d]*)(\d*)$/);
    if (match) { return { prefix: match[1], number: match[2] }; }
    return null;
  }
  return cloud.utils.requestReturn({ data: form })
}

//学员评议删除
async function studentEvaluateDelete() {
  await cloud.utils.deleteData("class-student-evaluate", data)
  return cloud.utils.requestReturn({ data: "" })
}

//学员评议列表-查询
async function studentEvaluateList() {
  let aa = await db.collection("class-student-evaluate").find({ lessonScheduleId: data.lessonScheduleId }).toArray()
  return cloud.utils.requestReturn({ data: aa })
}

//学员评议列表-班级
async function studentEvaluateClass() {
  let aa = await db.collection("class-student-evaluate").find({ classId: data.classId }).toArray()
  return cloud.utils.requestReturn({ data: aa })
}

async function studentEvaluateFile() {
  let errList = []
  let { classId, list, lessonScheduleId } = data
  for (let index = 0; index < list.length; index++) {
    const element = list[index];
    const doc = await db.collection('web-users').findOne({
      "baseInfo.identityCard": element.idCard.trim(),
    })
    //console.log("查询到的用户", doc)
    if (doc && doc._id) {
      element.userId = doc._id
      element.lessonScheduleId = lessonScheduleId
      element.classId = classId
      //新增评议
      await db.collection('class-student-evaluate').insertOne(element)
    } else {
      element.errText = "学员身份证号码不存在"
      errList.push(element)
    }
  }
  return cloud.utils.requestReturn({ data: { errList } })
}

//课程安排表重新生成
async function B1ListInit() {
  let dbName = "admin-course-schedule"
  await cloud.nw.db.del({ dbName, whereJson: { classId: data.classId } });
  await B1List()
  return cloud.utils.requestReturn({ data: "" })
}

async function B1List() {
  let dbName = "admin-course-schedule"
  //拿到课时课次
  console.log("data.classId", data.classId)
  let { classSession } = await cloud.nw.db.findByWhereJson({
    dbName: "admin-class",
    whereJson: { _id: data.classId },
  });
  console.log("classSession", classSession)

  //admin-course-schedule 课程安排表
  let aa = await db.collection(dbName).find({ classId: data.classId }).sort({ dateStamp: 1, sort: 1 }).toArray()
  //排期
  let bb = await db.collection("admin-teaching-schedule").find({
    classId: data.classId,
    isSubmit: {
      $exists: true,    // 确保字段存在
      $in: [1, "1"]     // 匹配值为数字1或字符串'1'
    }
  }).sort({ dateStamp: 1, sort: 1 }).toArray()
  //教学安排表设置过
  if (aa.length) {
    for (let index = 0; index < aa.length; index++) {
      const element = aa[index];
      let res = await cloud.nw.db.findByWhereJson({
        dbName: "admin-teaching-schedule",
        whereJson: {
          date: element.date,
          classStartTime: element.classStartTime,
          classEndTime: element.classEndTime,
        },
      });
      if (res && res._id) {
      } else {  //如果之前的排期有删除，则课程安排表也删除
        await cloud.nw.db.del({
          dbName,
          whereJson: { _id: element._id }
        });
      }
    }
    for (let index = 0; index < bb.length; index++) {
      const element = bb[index];
      let res = await cloud.nw.db.findByWhereJson({
        dbName,
        whereJson: {
          date: element.date,
          classStartTime: element.classStartTime,
          classEndTime: element.classEndTime,
        },
      });
      if (res && res._id) {
      } else if (element.unitClassHours % classSession != 0) {
        return cloud.utils.requestReturn({ data: "课时数量不匹配", code: 500 })
      }
      else {  //如果之前的排期有新增，则课程安排表也新增
        let num = element.unitClassHours / classSession
        let obj = { ...element }
        delete obj._id
        obj["courseDate"] = element.date
        for (let j = 0; j < num; j++) {
          await cloud.nw.db.add({
            dbName,
            dataJson: obj,
            cancelAddTime: false
          });
        }
      }
    }
  }
  else {
    for (let index = 0; index < bb.length; index++) {
      const element = bb[index];
      if (element.unitClassHours % classSession != 0) return cloud.utils.requestReturn({ data: "课时数量不匹配", code: 500 })
      let num = element.unitClassHours / classSession
      element.courseId = element._id  //节课id存下来
      let obj = { ...element }
      delete obj._id
      obj["courseDate"] = element.date
      for (let j = 0; j < num; j++) {
        await cloud.nw.db.add({
          dbName,
          dataJson: obj,
          cancelAddTime: false
        });
      }
    }
  }
  let arr = await db.collection(dbName).find({ classId: data.classId }).sort({ dateStamp: 1, sort: 1 }).toArray()

  //如果是查询评议表
  if (data.type && data.type == "evaluate") {
    for (let index = 0; index < arr.length; index++) {
      const element = arr[index];
      const count = await db.collection('class-student-evaluate')
        .countDocuments({ lessonScheduleId: element._id })
      element.evaluateCount = count
      const doc = await db.collection('class-student-evaluate').findOne({
        lessonScheduleId: element._id
      })
      element.fillTime = doc ? doc.fillTime : ""
    }
  }

  return cloud.utils.requestReturn({ data: arr })
}

async function B7Details() {
  let dbName = "admin-class-report-B7-Afterword"
  let res = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson: { classId: data.classId },
  });
  return cloud.utils.requestReturn({ data: res })
}

async function B7Save() {
  let dbName = "admin-class-report-B7-Afterword"
  let res = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson: { classId: data.classId },
  });
  if (res && res._id) { //编辑
    await cloud.nw.db.update({
      dbName,
      whereJson: { classId: data.classId },
      dataJson: data
    });
  } else {
    await cloud.nw.db.add({
      dbName,
      dataJson: data,
      cancelAddTime: false
    });
  }
  return cloud.utils.requestReturn({ data: "" })
}

async function B5List() {
  let whereJson = { ...data }
  whereJson.userId = { $exists: true }//只查询线上
  //班级学员
  let aa = await cloud.nw.db.findListByWhereJson({
    dbName: "admin-class-student",
    whereJson,
    fieldJson: { suspensionClassDate: 1, userId: 1 },
    sortArr: [
      { "name": "userState", "type": "desc" },
      { "name": "userPinyin", 'type': "asc" },
      { "name": "_add_time", "type": "asc" }
    ],
  });
  //课程排期
  let bb = await db.collection("admin-teaching-schedule").find(data).sort({ dateStamp: 1 }).project({ date: 1 }).toArray()
  let dates = []
  for (let index = 0; index < bb.length; index++) {
    const element = bb[index];
    dates.push(element.date)
  }
  for (let index = 0; index < aa.length; index++) {
    const element = aa[index];
    let { baseInfo } = await cloud.nw.db.findByWhereJson({
      dbName: "web-users",
      whereJson: { _id: element.userId },
    });
    element.name = baseInfo.name //学员的姓名
    element.index = index + 1
    let arr = []
    let cc = await db.collection("admin-class-signIn").find({ userId: element.userId, classId: data.classId }).project({ schedulingId: 1, status: 1 }).toArray()
    for (let j = 0; j < cc.length; j++) {
      const item = cc[j];
      const res = await db.collection('admin-teaching-schedule').findOne({
        _id: item.schedulingId
      })
      if (res && res.date) {
        arr.push({
          date: res.date,
          status: item.status,
          suspensionClassDate: element.suspensionClassDate,
        })
      } else {
        console.log("排期不存在", element.name)
      }
    }
    element.dates = arr
  }
  return cloud.utils.requestReturn({ data: { list: aa, dates } })
}

async function B3List() {
  let dbName = "admin-class-report-B3-list"
  // console.log("B3List-data", data)
  //await cloud.nw.db.del({ dbName, whereJson: data })

  //符合要求的数量
  let doc = await db.collection(dbName).find(data).toArray()
  let bb = await db.collection("admin-class-student").find(data).toArray()
  // console.log("班级学员count1", bb.length)
  // console.log("学员信息count2", doc.length)
  console.log("符合要求的数量", bb.length, doc.length)

  if (bb.length != doc.length) {
    if (doc.length > bb.length) {
      for (let index = 0; index < doc.length; index++) {
        const element = doc[index];
        //如果学员信息有这个人，则跳过
        if (cloud.utils.isFieldEqual(bb, "userId", element.userId)) {
        } else {
          await cloud.utils.deleteData(dbName, {
            classId: data.classId,
            userId: element.userId,
          });
        }
      }
    }
    for (let index = 0; index < bb.length; index++) {
      const element = bb[index];
      let obj = { ...data }
      obj.userId = element.userId
      obj.userState = element.userState //学员状态
      obj.userPinyin = element.userPinyin //拼音
      let isHas = cloud.utils.isFieldEqual(doc, "userId", element.userId)
      if (isHas) {
      } else {  //新增这个人
        await cloud.nw.db.add({ dbName, dataJson: obj, cancelAddTime: true });
      }
    }
  } else {
    for (let index = 0; index < bb.length; index++) {
      const element = bb[index];
      let current = cloud.utils.findIndexByField(doc, "userId", element.userId)
      if (current != -1) {
        if (element.userState != doc[current].userState) {
          console.log("更新状态", element.userState)
          await cloud.nw.db.update({
            dbName,
            whereJson: { userId: element.userId, },
            dataJson: { userState: element.userState }
          });
        }
      }
    }
  }

  let arr = await cloud.nw.db.findListByWhereJson({
    dbName,
    whereJson: data,
    sortArr: [
      { "name": "userState", "type": "desc" },
      { "name": "userPinyin", 'type': "asc" },
      { "name": "_add_time", "type": "asc" }
    ],
  });

  for (let index = 0; index < arr.length; index++) {
    const element = arr[index];
    //判断有没有重复的学员
    let aa = await db.collection(dbName).find({ classId: data.classId, userId: element.userId }).toArray()
    if (aa.length > 1) await cloud.nw.db.del({ dbName, whereJson: { _id: aa[0]._id } });
    element.baseInfo = await getUserInfo(element.userId)
  }
  return cloud.utils.requestReturn({ data: arr })

  async function getUserInfo(userId) {
    let { baseInfo } = await cloud.nw.db.findByWhereJson({
      dbName: "web-users",
      whereJson: { _id: userId },
    });
    return baseInfo
  }
}

async function B3Update() {
  let dbName = "admin-class-report-B3-list"
  let dataJson = { ...data }
  delete dataJson.userId
  delete dataJson.classId
  await cloud.nw.db.update({
    dbName,
    whereJson: {
      classId: data.classId,
      userId: data.userId,
    },
    dataJson
  });
  return cloud.utils.requestReturn({ data: "" })
}
